package com.zha.filter;

import com.alibaba.fastjson.JSONObject;
import com.zha.constant.AuthConstants;
import com.zha.model.SecurityUser;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Title: 只有光头才能变强
 * @Author: 炸炸
 * @Date: 2024/12/12 13:41
 * token转换过滤器
 */
@Component
public class TokenTranslationFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 1.获取请求头中的token
     * 2.判断是否有值
     * 3.如果有值,获取token所对应的在redis中的用户身份信息,在将用户身份信息存放到当前工厂的security上下文中
     * @param request HttpServletRequest对象，用于获取请求相关的信息
     * @param response HttpServletResponse对象，用于设置响应相关的信息
     * @param filterChain 过滤器链，用于继续请求处理
     * @throws ServletException 如果处理请求时发生Servlet相关异常
     * @throws IOException 如果发生I/O异常
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求头中的authorization值
        String authorizationValue = request.getHeader(AuthConstants.AUTHORIZATION);
        // 判断是否有值
        if (StringUtils.hasText(authorizationValue)&&authorizationValue.startsWith(AuthConstants.BEARER)) {
            // 获取token
            String token = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            // 判断token是否有值
            if (StringUtils.hasText(token)) {
                // 解决用户操作功能的时长超过当前token有效期剩余的时长,即token的续约
                // 从redis中获取当前token的有效时长
                Long expire = stringRedisTemplate.getExpire(AuthConstants.LOGIN_TOKEN_PREFIX + token, TimeUnit.SECONDS);
                // 判断当前token的有效时长是否超过token有限时长的阈值
                if (expire < AuthConstants.TOKEN_EXPIRE_THRESHOLD_TIME){
                    // 给当前用户的token续约
                    stringRedisTemplate.expire(AuthConstants.LOGIN_TOKEN_PREFIX + token, AuthConstants.TOKEN_TIME, TimeUnit.SECONDS);
                }
                // 根据令牌token从redis中获取json格式字符串的用户身份信息
                String securityUserJsonStr = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
                // 将json格式字符串用户身份信息转换为security用户安全用户对象
                SecurityUser securityUser = JSONObject.parseObject(securityUserJsonStr, SecurityUser.class);
                // 从securityUser安全认证用户对象中获取权限集合
                Set<String> perms = securityUser.getPerms();
                // 将权限set集合转换为SimpleGrantedAuthority类型的集合数据
                Set<SimpleGrantedAuthority> collect = perms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
                // 创建一个用户名密码认证身份对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, collect);
                // 将securityUser安全用户对象存放到security容器上下文中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        // 继续执行filterChain
        filterChain.doFilter(request, response);
    }
}
